package com.haixiaoke.flat.system.controller;

import com.haixiaoke.auth.AuthCheck;
import com.haixiaoke.auth.LoginParam;
import com.haixiaoke.saas.common.weChat.domain.WeChatLoginParam;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import com.haixiaoke.token.FrontTokenComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/front")
public class FrontLoginController extends BaseController {


    @Autowired
    private FrontTokenComponent tokenComponent;

    @Autowired
    private IUserConsumerService userConsumerService;

    /**
     * 账号密码登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginParam loginParam) {
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobileAndPwd(loginParam.getUserName(),loginParam.getPassword());
        if (userConsumer == null) {
            return AjaxResult.error("用户名或密码错误!");
        }
        String token = tokenComponent.createToken(userConsumer);
        // 返回 token 和 用户
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("token", token);
        map.put("userInfo", userConsumer);
        return AjaxResult.success("登录成功!", map);
    }

    /**
     * 账号密码登录
     */
    @PostMapping("/weChat/login")
    public AjaxResult weChatLogin(@RequestBody WeChatLoginParam loginParam) {
        UserConsumer userConsumer = userConsumerService.weChatSelectUserByPhone(loginParam);
        String token = tokenComponent.createToken(userConsumer);
        // 返回 token 和 用户
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("token", token);
        map.put("userInfo", userConsumer);
        return AjaxResult.success("登录成功!", map);
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        System.out.println("登出!");
        tokenComponent.logout(request);
        return AjaxResult.success();
    }

    /**
     * @return
     */
    @AuthCheck
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        Long userId = tokenComponent.getUserIdNotNull();
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByUserId(userId);
        return success(userConsumer);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @AuthCheck
    @PutMapping("/updateInfo")
    public AjaxResult updateInfo(@RequestBody UserConsumer user) {
        Long uid = tokenComponent.getUserIdNotNull();
        user.setUserId(uid);
        return success(userConsumerService.updateUserConsumer(user));
    }
}